package com.zapi.ai.controller;

import com.zapi.ai.model.ApiMetadata;
import com.zapi.ai.model.ChatMessage;
import com.zapi.ai.model.ChatRequest;
import com.zapi.ai.model.ChatResponse;
import com.zapi.ai.service.AiChatService;
import com.zapi.ai.service.AiChatHistoryService;
import com.zapi.ai.service.ApiScannerService;
import com.zapi.common.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * AI聊天助手Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/ai/chat")
@Api(tags = "AI聊天助手")
@RequiredArgsConstructor
public class AiChatController {
    
    private final AiChatService aiChatService;
    private final AiChatHistoryService chatHistoryService;
    private final ApiScannerService apiScannerService;
    
    @PostMapping("/send")
    @ApiOperation("发送消息")
    public Result<ChatResponse> sendMessage(
            @RequestBody ChatRequest request,
            @RequestHeader(value = "Authorization", required = false) String authorization) {
        try {
            log.info("收到AI聊天请求: message={}, images={}, files={}", 
                    request.getMessage(), 
                    request.getImages() != null ? request.getImages().size() : 0,
                    request.getFiles() != null ? request.getFiles().size() : 0);
            
            // 提取JWT token，用于调用业务API
            if (authorization != null && authorization.startsWith("Bearer ")) {
                String token = authorization.substring(7);
                request.setToken(token);
            }
            
            ChatResponse response = aiChatService.chat(request);
            return Result.success("聊天成功", response);
        } catch (Exception e) {
            log.error("AI聊天处理失败", e);
            return Result.error("AI聊天失败: " + e.getMessage());
        }
    }
    
    @DeleteMapping("/session/{sessionId}")
    @ApiOperation("清除会话")
    public Result<String> clearSession(@PathVariable String sessionId) {
        aiChatService.clearSession(sessionId);
        return Result.success("会话已清除", "OK");
    }
    
    @GetMapping("/health")
    @ApiOperation("健康检查")
    public Result<String> health() {
        return Result.success("AI服务运行正常", "OK");
    }
    
    @GetMapping("/history")
    @ApiOperation("获取用户聊天历史")
    public Result<List<ChatMessage>> getUserHistory(
            @RequestParam(required = false, defaultValue = "default_user") String userId,
            @RequestParam(required = false, defaultValue = "50") int limit) {
        List<ChatMessage> history = chatHistoryService.getUserHistory(userId, limit);
        return Result.success("获取历史成功", history);
    }
    
    @GetMapping("/session/{sessionId}")
    @ApiOperation("获取指定会话历史")
    public Result<List<ChatMessage>> getSessionHistory(@PathVariable String sessionId) {
        List<ChatMessage> history = chatHistoryService.getSessionHistory(sessionId);
        return Result.success("获取会话历史成功", history);
    }
    
    @GetMapping("/apis")
    @ApiOperation("获取系统所有可用API列表")
    public Result<List<ApiMetadata>> getAllApis() {
        List<ApiMetadata> apis = apiScannerService.getAllApis();
        return Result.success("获取API列表成功", apis);
    }
    
    @GetMapping("/apis/doc")
    @ApiOperation("获取AI可读的API文档")
    public Result<String> getApiDocumentation() {
        String doc = apiScannerService.generateApiDocumentation();
        return Result.success("获取API文档成功", doc);
    }
}

